﻿using Autofac;
using HSGD.IRepository.BASE;
using HSGD.Repository.BASE;
using HSGD.IServices.BASE;
using HSGD.Services.BASE;
using System.Reflection;
using Autofac.Extras.DynamicProxy;
using Serilog;
using HSGD.Extensions.AOP;
using HSGD.AOP;
using HSGD.Repository.UnitOfWorks;
using HSGD.Common;

namespace HSGD.Extensions;
public class AutofacModuleRegister : Autofac.Module {
    protected override void Load(ContainerBuilder builder) {
        var basePath = AppContext.BaseDirectory;

        var servicesDllFile = Path.Combine(basePath, ProjectDllFileName.SERVICE_NAME);
        var repositoryDllFile = Path.Combine(basePath, ProjectDllFileName.REPOSITORY_NAME);

        if (!(File.Exists(servicesDllFile) && File.Exists(repositoryDllFile))) {
            var msg = "Can't found out Service.DLL and Repository.dll";
            Log.Error(msg);
            throw new Exception(msg);
        }
        var aopTypes = new List<Type>() { typeof(HSGDLogAOP), typeof(HSGDTranAOP) };
        builder.RegisterType<HSGDLogAOP>();
        builder.RegisterType<HSGDTranAOP>();
        
        builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerDependency(); //注册仓储
        builder.RegisterGeneric(typeof(BaseServices<>)).As(typeof(IBaseServices<>))
            .EnableInterfaceInterceptors()
            .InterceptedBy(aopTypes.ToArray())
            .InstancePerDependency(); //注册服务

        // 获取 Service.dll 程序集服务，并注册
        var assemblysServices = Assembly.LoadFrom(servicesDllFile);
        builder.RegisterAssemblyTypes(assemblysServices)
            .AsImplementedInterfaces()
            .InstancePerDependency()
            .PropertiesAutowired()
            .EnableInterfaceInterceptors()
            .InterceptedBy(aopTypes.ToArray());

        // 获取 Repository.dll 程序集服务，并注册
        var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
        builder.RegisterAssemblyTypes(assemblysRepository)
            .AsImplementedInterfaces()
            .PropertiesAutowired()
            .InstancePerDependency();


        builder.RegisterType<UnitOfWorkManage>().As<IUnitOfWorkManage>()
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope()
            .PropertiesAutowired();
    }
}
